import { useIntersectionObserver } from '@vueuse/core'
import defaultImg from '@/assets/images/200.png'
import loadingGif from '@/assets/images/load.gif'
export default {
  install (app) {
    app.directive('imgLazy', {
      // vue2: inserted -> vue3: mounted
      /**
       *
       * @param {*} el img的dom对象
       * @param {*} binding.value 指令绑定的图片地址
       */
      mounted (el, binding) {
        // console.log(el, binding)
        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }], ovserverElement) => {
          if (isIntersecting) {
            // console.log(123)
            el.src = loadingGif
            el.onerror = function () {
              el.src = defaultImg
            }
            // 看效果可以使用定时器,记得注释或删除
            setTimeout(() => {
              el.src = binding.value
            }, 1000)
            stop()
          }
        }, {
          threshold: 0
        })
      }
    })
  }
}
